#!/usr/bin/env node

const http = require('http'),
  url = require('url'),
  qs = require('querystring');

let items = [];

http.createServer((req,res)=>{

  let path = url.parse(req.url).pathname;

  if(path !== '/'){
    err(req,res);
    return;
  }
  console.log(`${req.method} ${req.url} HTTP/${req.httpVersion}`);
  console.log(req.headers);
  console.log('');

  add(req,res);

}).listen(8080);

function err(req,res){
  res.statusCode = 404;
  res.end(`${req.url} NOT FOUND`);
  
}

function add(req,res){
  const value = qs.parse(url.parse(req.url).query).item;

  if(typeof value !== 'undefined' && value !== '') items.push(value);

  console.log(items);
  show(res);

}
function show(res){
  const html = `
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8">
      <title>TODO list</title>
    </head>
    <body>
      <h1>ToDo List</h1>
      <form method="get" action="/">
        <p><input type="text" name="item"/>
        <input type="submit"value="Add Item" /></p>
      </form>
      <ul>
        ${items.map(item => '<li>' + item + '</li>').join('\n')}
      </ul>
    </body>
    </html>
    `;
  res.setHeader('Content-Type','text/html');
  res.setHeader('Content-Length',Buffer.byteLength(html));

  res.statusCode = 200;
  res.end(html);
}




